package root.item;

import java.util.GregorianCalendar;

import root.user.User;
import exceptions.InvalidItemCategoryException;
import exceptions.InvalidItemNameException;

/**
 * utiliza o padrao Observer.
 */
public class Item implements Comparable<Item>{
	
	private User owner;
	private GregorianCalendar createdDate;
	private String name;
	private String description;
	private Category category;
	private boolean isBorrowed;
	private String id;
		
	public Item(String name, String description, String category, String id, User owner) throws InvalidItemNameException, InvalidItemCategoryException {
		if( name == null || name.equals("")){
			throw new InvalidItemNameException("Nome inválido");
		}
		if(description == null){
			throw new NullPointerException();
		}
		if(category == null){
			throw new InvalidItemCategoryException("Categoria inválida");
		}
		this.name = name;
		this.description = description;
		this.category = new Category(category);
		this.id = id;
		this.owner = owner;
		createdDate = new GregorianCalendar();
	}
	
	/**
	 * @return Nome do item
	 */
	public String getName() {
		return name;
	}
	
	/**
	 * 
	 * @return Id do item
	 */
	public String getId(){
		return id;
	}
	
	/**
	 * 
	 * @return Descricao do item
	 */
	public String getDescription() {
		return description;
	}
	
	/**
	 * @return String de categoria do item
	 */
	public String getCategory() {
		return category.toString();
	}
	
	@Override
	public boolean equals(Object o){
		if(!(o instanceof Item)){
			return false;
		}
		Item item = (Item) o;
		return item.id.equals(id);
	}
	
	@Override
	public int hashCode(){
		return id.hashCode();
	}
	
	/**
	 * Atribui o nome passado como parametro ao item
	 * @param newName Novo nome do item
	 */
	public void setName(String newName) {
		if(newName == null){
			throw new NullPointerException();
		}
		this.name = newName;
	}
	
	/**
	 * Atribui uma descricao ao item
	 * @param newDescription Nova descricao
	 */
	public void setDescription(String newDescription) {
		if(newDescription == null){
			throw new NullPointerException();
		}
		this.description = newDescription;
	}
	
	/**
	 * Atribui uma categoria ao item
	 * @param newCategory Nova categoria
	 */

	public void setCategory(Category newCategory) {
		if(newCategory == null){
			throw new NullPointerException();
		}
		this.category = newCategory;
	}
	
	public User getOwner(){
		return owner;
	}
	
	public GregorianCalendar getCreatedDate(){
		return createdDate;
	}

	@Override
	public int compareTo(Item o) {
		if(equals(o)) return 0;
		return getCreatedDate().compareTo(o.getCreatedDate());
	}

	public boolean isBorrowed(){
		return isBorrowed;
	}
	
	public void lend(){
		isBorrowed = true;
	}
	
	public void devolution(){
		isBorrowed = false;
	}
}
